package com.yq.config;

import com.yq.constant.CommonConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jdk.nashorn.internal.codegen.CompilerConstants;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 浏览器----a----b 有request有Authorization
 * mq----a
 * 支付宝-----a-----b 有request无Authorization
 *
 * template 发起远程调用的请求
 */
@Component
public class OauthFeignConfig implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!ObjectUtils.isEmpty(requestAttributes)){
            String authorization = requestAttributes.getRequest().getHeader(CommonConstants.AUTHORIZATION);
            if (StringUtils.hasText(authorization)){
               //把token传给下一代
                requestTemplate.header(CommonConstants.AUTHORIZATION,authorization);
            }
        }
        //否则便生成一个 客户端的token
        requestTemplate.header(CommonConstants.AUTHORIZATION,CommonConstants.BEARER+
                CommonConstants.CLIENT_TOKEN);
    }
}
